<?php
/*
 * [JINYUN!] (C)2001-2099 Jinyunweb.com
 * This is NOT a freeware, use is subject to license terms
 * $Id: 2017-12-13 03:39:35 apple $
*/
namespace jy_fahuo;
defined('BY_JYA') or exit('error');
class api extends \plugin{
	public function __construct(){
		$set=uni_setting('jy_fahuo');
		if(empty($set['cainiao_key'])){
			exi('请先联系管理员：设置菜鸟物流KEY','error','/setting/');
		}
		if(empty($set['cainiao_secret'])){
			exi('请先联系管理员：设置菜鸟物流secret','error','/setting/');
		}
		$basic=plugin('jy_fahuo')->plugin_setting('basic');
		if(!$_SESSION['isfounder']){
			$set['cainiao_token']=$basic['cainiao_token'];
		}
		if(empty($set['cainiao_token'])){
			exi('请先设置商家授权Token','error','/setting/');
		}
		$this->basic=$basic;
		$this->set=$set;
	}
	//https://www.cnblogs.com/legweifang/p/11725050.html
	//发起http请求
	public function request($msg_type,$content='',$continue=true,$direct=false,$return_error=false,$isjson=false,$isrequest=false){
		$content2=ijson_encode($content);
		$digest=$this->getDigest($content2);
		$post=array(
			'logistic_provider_id'=>$this->set['cainiao_token'],
			'msg_type'=>$msg_type,
			'logistics_interface'=>$content2,
			'data_digest'=>$digest,
		);
		//file_put_contents(ROOT_D.'/1.txt',$time.'~~传参'.ijson_encode($post)."\n",FILE_APPEND);
		if($this->set['is_open']){
			//$post=ijson_encode($post);
			$result=cfc('http')->ihttp_post('https://link.cainiao.com/gateway/link.do',$post);
		}else{
			//https://link.cainiao.com/gateway/custom/open_integration_test_env
			$result=cfc('http')->ihttp_post('https://link.cainiao.com/gateway/custom/open_integration_test_env',$post);
		}
		if(is_error($result)){
			$message="访问接口失败, 错误: {$result['message']}";
			if($return_error){
				return error($message);
			}else{
				exi($message,'error');
			}
		}
		$data=preg_replace('/[\x00-\x1F]/','',$result['content']);
		//file_put_contents(ROOT_D.'/1.txt',$time.'~~接口返回'.$data."\n",FILE_APPEND);
		if(strpos($data, '<response>') !== false){
			$data = isimplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);
			$data = json_decode(json_encode($data), true);
		}else{
			$data=@json_decode($data,true);
		}
		if(!$data['success']){
			$message=$this->error_code($data['errorCode']).' '.$data['errorMsg'].' '.$data['errorCode'];
			if($return_error || $_SESSION['this']=='custom'){
				return error($message);
			}else{
				exi($message,'error');
			}
		}
		if($direct){
			return $result;
		}
		if(!is_array($data) || !$data){
			$message='接口错误，以下为原始数据：'.$result['content'];
			if($return_error){
				return error($message);
			}else{
				exi($message,'error');
			}
		}
		return $data;
	}
	//isv 通过接口获取标准电子面单模板https://global.link.cainiao.com/#/homepage/api/link/merchant_electronic_sheet/CLOUDPRINT_SELLER_ISV_TEMPLATES?_k=gj3i6r
	public function get_template($cpCode='',$isv=0) {
		$msg_type = $isv?"CLOUDPRINT_SELLER_ISV_TEMPLATES":"CLOUDPRINT_STANDARD_TEMPLATES";
		$res=$this->request($msg_type,array('objectId'=>$cpCode));
		if(!$res['success']){
			exi('获取标准电子面单模板失败：'.$res['errorCode'].','.$res['errorMsg'],'error');
		}
		return $res['data'];
	}
	public function del_waybill($cpCode='',$waybillCode=''){
		$msg_type = "TMS_WAYBILL_DISCARD";
		$post=array(
			'cpCode'=>$cpCode,
			'waybillCode'=>$waybillCode,
		);
		$res=$this->request($msg_type,$post);
		if(!$res['discardResult']){
			exi('ISV电子面单取消接口失败：'.$res['errorCode'].','.$res['errorMsg'],'error');
		}
		return true;
	}
	//isv 电子面单云打印取号接口https://open.cainiao.com/api-doc/detail?category=link&type=merchant_electronic_sheet&apiId=TMS_WAYBILL_GET
	//https://open.sf-express.com/developSupport/734349?activeIndex=324604
	public function get_waybill($order=array(),$cpCode='',$templateUrl='',$nowkuai=array()){
		$msg_type = "TMS_WAYBILL_GET";
		if(!is_array($order['address'])){
			$order['address']=json_decode($order['address'],true);
		}
		$templateUrl=$templateUrl?:$this->set['templateurl'];
		if(!$templateUrl){
			exi('请先填写[云打印标准模板URL]！','error');
		}
		$basic=$this->basic;
		if(!$basic['pcd'] || !$basic['address'] || !$basic['name'] || !$basic['mobile']){
			exi('发货人信息未设置完整（区域，地址，姓名，电话）！！','error');
		}
		if($order['merchid']){
			$myshop=pdo_get('jy_merch_user',array('id'=>$order['merchid'],'uniacid'=>$_SESSION['uniacid']),array('mobile','realname','pcd','address'));
			$basic['pcd']=json_decode($myshop['pcd'],true);
			$basic['mobile']=$myshop['mobile'];
			$basic['name']=$myshop['realname'];
			$basic['address']=$myshop['address'];
			if(!$basic['pcd'] || !$basic['address'] || !$basic['name'] || !$basic['mobile']){
				exi('多商户的地址信息未设置完整（区域，地址，姓名，电话）！！','error');
			}
		}
		$address=array(
			'province'=>$basic['pcd']['province'],
			'city'=>$basic['pcd']['city'],
			'district'=>$basic['pcd']['district'],
			'town'=>$basic['pcd']['street'],
			'detail'=>$basic['address'],
		);
		$sender=array(
			'address'=>$address,
			'phone'=>$basic['phone']?:'',
			'mobile'=>$basic['mobile'],
			'name'=>$basic['name'],
		);
		$address=array(
			'province'=>$order['address']['pcd']['province'],
			'city'=>$order['address']['pcd']['city'],
			'district'=>$order['address']['pcd']['district']?:'',
			'town'=>$order['address']['pcd']['street']?:'',
			'detail'=>$order['address']['address']?:'',
		);
		$recipient=array(
			'address'=>$address,
			'phone'=>$order['phone']?:'',
			'mobile'=>$order['address']['mobile']?:$order['mobile'],
			'name'=>$order['address']['name']?:$order['name'],
		);
		$ordergoods=pdo_getall('jy_weishop_order_goods',array('orderid'=>$order['id'],'uniacid'=>$_SESSION['uniacid']),array('goodsid','optionid','price','total','goodssn','productsn'));
		$items =array();
		foreach($ordergoods as $gv){
			$gv['title']=pdo_getcolumn('jy_weishop_goods',array('id'=>$gv['goodsid'],'uniacid'=>$_SESSION['uniacid']),'title');
			if(!$goodsdesc){
				$goods=pdo_get('jy_weishop_goods',array('id'=>$gv['goodsid'],'uniacid'=>$_SESSION['uniacid']),array('subtitle','shorttitle'));
				$goodsdesc=$goods['subtitle']?:$goods['shorttitle'];
				if(!$goodsdesc){
					$goodsdesc='描述：'.$gv['title'];
				}else{
					$goodsdesc='#'.$goodsdesc;
				}
			}
			$items[]=array(
				'name'=>cfc('tools')->substr($gv['title'],0,20),
				'count'=>$gv['total'],
			);
		}
		$packageInfo=array(
			'volume'=>1,
			'packagingDescription'=>$items[0]['name']?cfc('tools')->substr($items[0]['name'],0,20):'',
			'weight'=>$order['weight']?:100,
			'items'=>$items,
			'id'=>$order['id'],
			'goodsDescription'=>cfc('tools')->substr($goodsdesc,0,20),
			'totalPackagesCount'=>$order['total']?:'1',
		);
		$tradeOrderInfoDtos=array();
		$tradeOrderInfoDto=array(
			'objectId'=>$order['id'],
			'orderInfo'=>array('orderChannelsType'=>'OTHERS','tradeOrderList'=>array($order['ordersn'])),
			'recipient'=>$recipient,
			'packageInfo'=>$packageInfo,
			'userId'=>$this->set['merch_id']?:0,
			'objectId'=>$order['id'],
			'templateUrl'=>$templateUrl,
		);
		$tradeOrderInfoDtos[]=$tradeOrderInfoDto;
		$post=array(
			'cpCode'=>$cpCode,
			'sender'=>$sender,
			'tradeOrderInfoDtos'=>$tradeOrderInfoDtos,
			'brandCode'=>$cpCode=='SF'?'SF':'',
			'productCode'=>$cpCode=='SF'?'2':'',
		);
		if($nowkuai['paytype']!=3){
			$extraInfo=array('payMethod'=>intval($nowkuai['paytype'])?:1);
			$post['extraInfo']=ijson_encode($extraInfo);
		}
		if($order['callDoorPickUp']){
			if(!$order['doorPickUpTime'] || !$order['doorPickUpEndTime']){
				exi('请设置预约上门收件时间！','error');
			}
			$post['callDoorPickUp']=$order['callDoorPickUp'];
			$post['doorPickUpTime']=$order['doorPickUpTime'];
			$post['doorPickUpEndTime']=$order['doorPickUpEndTime'];
		}
		//print_r($post);exit;
		//file_put_contents(ROOT_D.'/1.txt',ijson_encode($post));
		$res=$this->request($msg_type,$post);
		if(!$res['waybillCloudPrintResponseList']){
			exi('电子面单云打印取号接口失败：'.$res['errorCode'].','.$res['errorMsg'],'error');
		}
		return $res['waybillCloudPrintResponseList'];
	}
	//输入打印数据及模板地址，生成打印机特定指令串，调用方写入打印机进行打印。该接口主要用于ISV进行便携式蓝牙打印场景，目前仅支持CPCL指令集
	public function cmd_print($cpCode='') {
		$msg_type = "CLOUDPRINT_CMD_RENDER";
		$res=$this->request($msg_type,array('cpCode'=>$cpCode));
		if(!$res['success']){
			exi('打印失败：'.$res['errorCode'].','.$res['errorMsg'],'error');
		}
		return $res['data'];
	}
	//https://open.cainiao.com/document?namespace=gyuvti&slug=rd6q0i
	private function getDigest($apiContent){
		$Digest=base64_encode(md5($apiContent.$this->set['cainiao_secret'], true));
		return $Digest;
	}
	//错误码
	public function error_code($code, $errmsg = '未知错误') {//获取错误详情
		global $_AR;
		$errors = array(
			'-1' => '系统繁忙',
			'0' => '请求成功',
			'300002' => '商品标题太长了！最长14个汉字',
			'300003' => '价格输入不合规（如：现价比原价大、传入价格非数字等）',
			'300018' => '图片尺寸超过300px*300px',
			'300006' => '图片上传失败（如：mediaID过期）',
			'300007' => '线上小程序版本不存在该链接,请重新上传小程序代码！',
			'300022'=>'此房间号不存在',
			'300023'=>'房间状态 拦截（当前房间状态不允许此操作）',
			'300024'=>'商品不存在',
			'300025'=>'商品审核未通过',
			'300026'=>'房间商品数量已经满额',
			'300027'=>'导入商品失败',
			'300028'=>'房间名称违规',
			'300029'=>'主播昵称违规',
			'300030'=>'主播微信号不合法',
			'300031'=>'直播间封面图不合规',
			'300032'=>'直播间分享图违规',
			'300033'=>'添加商品超过直播间上限',
			'300034'=>'主播微信昵称长度不符合要求',
			'300035'=>'主播微信号不存在',
			'300036'=>'主播微信号未实名认证,登录微信搜索--《直播小程序》--实名认证一下即可！',
			'40001' => '获取access_token时AppSecret错误，或者access_token无效',
			'40002' => '不合法的凭证类型',
			'40003' => '不合法的OpenID',
			'40004' => '不合法的媒体文件类型',
			'40005' => '不合法的文件类型',
			'40006' => '不合法的文件大小',
			'40007' => '不合法的媒体文件id',
			'40008' => '不合法的消息类型',
			'40009' => '不合法的图片文件大小',
			'40010' => '不合法的语音文件大小',
			'40011' => '不合法的视频文件大小',
			'40012' => '不合法的缩略图文件大小',
			'40013' => '不合法的APPID',
			'40014' => '不合法的access_token',
			'40015' => '不合法的菜单类型',
			'40016' => '不合法的按钮个数',
			'40017' => '不合法的按钮个数',
			'40018' => '不合法的按钮名字长度',
			'40019' => '不合法的按钮KEY长度',
			'40020' => '不合法的按钮URL长度',
			'40021' => '不合法的菜单版本号',
			'40022' => '不合法的子菜单级数',
			'40023' => '不合法的子菜单按钮个数',
			'40024' => '不合法的子菜单按钮类型',
			'40025' => '不合法的子菜单按钮名字长度',
			'40026' => '不合法的子菜单按钮KEY长度',
			'40027' => '不合法的子菜单按钮URL长度',
			'40028' => '不合法的自定义菜单使用用户',
			'40029' => '不合法的oauth_code',
			'40030' => '不合法的refresh_token',
			'40031' => '不合法的openid列表',
			'40032' => '不合法的openid列表长度',
			'40033' => '不合法的请求字符，不能包含\uxxxx格式的字符',
			'40035' => '不合法的参数',
			'40038' => '不合法的请求格式',
			'40039' => '不合法的URL长度',
			'40050' => '不合法的分组id',
			'40051' => '分组名字不合法',
			'41001' => '缺少access_token参数',
			'41002' => '缺少appid参数',
			'41003' => '缺少refresh_token参数',
			'41004' => '缺少secret参数',
			'41005' => '缺少多媒体文件数据',
			'41006' => '缺少media_id参数',
			'41007' => '缺少子菜单数据',
			'41008' => '缺少oauth code',
			'41009' => '缺少openid',
			'42001' => 'access_token超时',
			'42002' => 'refresh_token超时',
			'42003' => 'oauth_code超时',
			'43001' => '需要GET请求',
			'43002' => '需要POST请求',
			'43003' => '需要HTTPS请求',
			'43004' => '需要接收者关注',
			'43005' => '需要好友关系',
			'44001' => '多媒体文件为空',
			'44002' => 'POST的数据包为空',
			'44003' => '图文消息内容为空',
			'44004' => '文本消息内容为空',
			'45001' => '多媒体文件大小超过限制',
			'45002' => '消息内容超过限制',
			'45003' => '标题字段超过限制',
			'45004' => '描述字段超过限制',
			'45005' => '链接字段超过限制',
			'45006' => '图片链接字段超过限制',
			'45007' => '语音播放时间超过限制',
			'45008' => '图文消息超过限制',
			'45009' => '接口调用超过限制',
			'45010' => '创建菜单个数超过限制',
			'45015' => '回复时间超过限制',
			'45016' => '系统分组，不允许修改',
			'45017' => '分组名字过长',
			'45018' => '分组数量超过上限',
			'45056' => '创建的标签数过多，请注意不能超过100个',
			'45057' => '该标签下粉丝数超过10w，不允许直接删除',
			'45058' => '不能修改0/1/2这三个系统默认保留的标签',
			'45059' => '有粉丝身上的标签数已经超过限制',
			'45157' => '标签名非法，请注意不能和其他标签重名',
			'45158' => '标签名长度超过30个字节',
			'45159' => '非法的标签',
			'46001' => '不存在媒体数据',
			'46002' => '不存在的菜单版本',
			'46003' => '不存在的菜单数据',
			'46004' => '不存在的用户',
			'47001' => '解析JSON/XML内容错误',
			'48001' => 'api功能未授权',
			'50001' => '用户未授权该api',
			'40070' => '基本信息baseinfo中填写的库存信息SKU不合法。',
			'41011' => '必填字段不完整或不合法，参考相应接口。',
			'40056' => '无效code，请确认code长度在20个字符以内，且处于非异常状态（转赠、删除）。',
			'43009' => '无自定义SN权限，请参考开发者必读中的流程开通权限。',
			'43010' => '无储值权限,请参考开发者必读中的流程开通权限。',
			'43011' => '无积分权限,请参考开发者必读中的流程开通权限。',
			'40078' => '无效卡券，未通过审核，已被置为失效。',
			'40079' => '基本信息base_info中填写的date_info不合法或核销卡券未到生效时间。',
			'45021' => '文本字段超过长度限制，请参考相应字段说明。',
			'40080' => '卡券扩展信息cardext不合法。',
			'40097' => '基本信息base_info中填写的参数不合法。',
			'49004' => '签名错误。请联系管理员设置好参数！',
			'43012' => '无自定义cell跳转外链权限，请参考开发者必读中的申请流程开通权限。',
			'40099' => '该code已被核销。',
			'61005' => '缺少接入平台关键数据，等待微信开放平台推送数据，请十分钟后再试或是检查“授权事件接收URL”是否写错（index.php?c=account&amp;a=auth&amp;do=ticket地址中的&amp;符号容易被替换成&amp;amp;）',
			'61023' => '请重新授权接入该小程序',
			'85005'=>'小程序未关联小程序，无法通过自定义菜单跳转！',
			'40164'=>'服务器IP不在白名单导致接口请求失败！请前往公众平台——开发——基本配置——小程序开发信息——IP白名单处设置',
		);
		$code = strval($code);
		if($errors[$code]) {
			return $errors[$code];
		} else {
			return $errmsg;
		}
	}
}